package com.shioirikukuri.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.shioirikukuri.common.until.RedisUtil;
import com.shioirikukuri.dto.SessionUserDTO;
import com.shioirikukuri.entity.User;
import com.shioirikukuri.mapper.AdminMapper;
import com.shioirikukuri.service.IAdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.UUID;

@Service
public class AdminServiceImpl implements IAdminService {

	@Autowired
	private AdminMapper adminMapper;

	@Autowired
	private RedisUtil redisUtil;

	/**
	 * 管理员或前台服务员用户登录
	 * @param phoneNumber
	 * @param password
	 * @param role
	 * @return
	 * @throws Exception
	 */
	@Override
	public String login(String phoneNumber, String password, String role) throws Exception {
		// 验证用户是否存在
		User user = adminMapper.findByPhoneNumber(phoneNumber);
		if (user == null || !role.equals(user.getRole())) {
			throw new Exception("Invalid username or role.");
		}

		// 密码校验
		String saltedPassword = generateSaltedPassword(password, user.getPhoneNumber());
		if (!checkPassword(saltedPassword, user.getPassword())) {
			throw new Exception("Incorrect password.");
		}

		// 生成Token
		String token = UUID.randomUUID().toString();
		SessionUserDTO sessionUserDTO = new SessionUserDTO(
				user.getId(),
				user.getFullName(),
				user.getRole()
		);

		// 存储到Redis，有效期1小时
		long expireSeconds = 3600;
		try {
			redisUtil.set(token, sessionUserDTO, expireSeconds);
		} catch (JsonProcessingException e) {
			throw new Exception("Failed to save session.");
		}

		// 返回token而非User对象
		return token;
	}


	private String generateSaltedPassword(String password, String salt) {
		// 把salt附加到password后面
		return DigestUtils.md5DigestAsHex((password + salt).getBytes());
	}

	private boolean checkPassword(String rawPassword, String encodedPassword) {
		return rawPassword.equals(encodedPassword);
	}
}

